﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Octopus.Logging.Commons
{
    public class TimeCaller
    {
        ThreadHelper threadHelper = new ThreadHelper();
        System.Threading.Timer timer;
        TimerCallback callbackDelegate;
        Function function;
        public delegate void Function();

        public TimeCaller(string id = null)
        {
            _ID = id;
        }

        string _ID = string.Empty;
        public string ID
        {
            get { return _ID; }
            set { _ID = value; }
        }

        bool _Running;
        public bool Running
        {
            get { return _Running; }
            set { _Running = value; }
        }

        /// <summary>
        /// 开始定时回调
        /// </summary>
        /// <param name="secondSpan">间隔秒</param>
        /// <param name="fun">回调函数</param>
        public void Start(int secondSpan,Function fun)
        {
            function = fun;
            callbackDelegate = new TimerCallback(DoCallback);
            timer = new Timer(callbackDelegate, threadHelper, 0, secondSpan * 1000);
            _Running = true;
        }

        /// <summary>
        /// 停止回调任务
        /// </summary>
        public void Stop()
        {
            if (timer != null) { timer.Dispose(); }
            timer = null;
            _Running = false;
        }

        protected void DoCallback(object param)
        {
            ThreadHelper helper = param as ThreadHelper;
            if (!helper.Status)
            {
                try
                {
                    helper.Status = true;

                    function();
                }
                catch (Exception err)
                {
                    Octopus.Logging.OwnLogging.LoggerManager.GetLogger().Error("回调发生异常",err);
                }
                finally
                {
                    helper.Status = false;
                }
            }
        }

        internal class ThreadHelper
        {
            public bool Status { get; set; }
        }        
    }
}
